import { HttpException, Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { User } from "./user.entity";

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>
  ) {}

  async findAll() {
    const list = await this.usersRepository.find({
      where: { isDelete: false },
    });
    const total = await this.usersRepository.count({
      where: { isDelete: false },
    });
    return { total, list };
  }

  async create(UserTodo) {
    await this.usersRepository.save(UserTodo);
    return true;
  }

  async update(id, UserTodo) {
    await this.usersRepository.update(id, UserTodo);
    return true;
  }

  async getOne(id) {
    const user = await this.usersRepository.findOne({
      where: { id, isDelete: false },
    });
    if (!user) throw new HttpException("数据不存在", 404);
    return user;
  }

  async delete(id) {
    const user = await this.getOne(id);
    await this.usersRepository.update(id, { ...user, isDelete: true });
    return true;
  }
}
